<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use think\facade\Db;
use think\facade\Validate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


class WebManagement extends BaseController
{
    // 新增信息
    public function create()
    {
        $data = $this->request->post();
        $validate = Validate::rule([
            'domain' => 'require',
            'version' => 'require',
            'developer' => 'require'
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 1, 'msg' => $validate->getError(), 'data' => []]);
        }

        $snowflake = new Snowflake(1, 1);
        $data['snowflake_id'] = $snowflake->nextId();

        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $id = Db::name('website_info')->insertGetId($data);
        if ($id) {
            return json(['code' => 0, 'msg' => '新增成功', 'data' => ['id' => $id]]);
        }
        return json(['code' => 1, 'msg' => '新增失败', 'data' => []]);
    }

    // 编辑信息
    public function update($id)
    {
        $data = $this->request->post();
        $validate = Validate::rule([
            'domain' => 'require',
            'version' => 'require',
            'developer' => 'require'
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 1, 'msg' => $validate->getError(), 'data' => []]);
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $result = Db::name('website_info')->where('id', $id)->update($data);
        if ($result) {
            return json(['code' => 0, 'msg' => '编辑成功', 'data' => []]);
        }
        return json(['code' => 1, 'msg' => '编辑失败', 'data' => []]);
    }

    // 删除信息
    public function delete($id)
    {
        $result = Db::name('website_info')->where('id', $id)->delete();
        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功', 'data' => []]);
        }
        return json(['code' => 1, 'msg' => '删除失败', 'data' => []]);
    }

    // 信息管理列表
    public function list()
    {
        $domain = $this->request->get('domain');
        $developer = $this->request->get('developer');
        $version = $this->request->get('version');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $query = Db::name('website_info');
        if ($domain) {
            $query->where('domain', 'like', "%$domain%");
        }
        if ($developer) {
            $query->where('developer', 'like', "%$developer%");
        }
        if ($version) {
            $query->where('version', 'like', "%$version%");
        }
        $list = $query->field('id, snowflake_id, domain, developer, icp_record, download_link,version, updated_at')
            ->page($page, $limit)
            ->select();
        $total = $query->count();
        return json(['code' => 0, 'msg' => '获取列表成功', 'data' => ['list' => $list, 'total' => $total]]);
    }

    // 导出信息
    public function export()
    {
        $domain = $this->request->get('domain');
        $developer = $this->request->get('developer');
        $version = $this->request->get('version');
        $format = $this->request->get('format', 'csv');
        $query = Db::name('website_info');
        if ($domain) {
            $query->where('domain', 'like', "%$domain%");
        }
        if ($developer) {
            $query->where('developer', 'like', "%$developer%");
        }
        if ($version) {
            $query->where('version', 'like', "%$version%");
        }
        $list = $query->field('id, snowflake_id, domain, developer, icp_record, version, updated_at')->select();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '雪花ID');
        $sheet->setCellValue('C1', '域名');
        $sheet->setCellValue('D1', '开发者');
        $sheet->setCellValue('E1', 'ICP备案');
        $sheet->setCellValue('F1', '版本号');
        $sheet->setCellValue('G1', '修改时间');
        foreach ($list as $key => $item) {
            $row = $key + 2;
            $sheet->setCellValue('A' . $row, $item['id']);
            $sheet->setCellValue('B' . $row, $item['snowflake_id']);
            $sheet->setCellValue('C' . $row, $item['domain']);
            $sheet->setCellValue('D' . $row, $item['developer']);
            $sheet->setCellValue('E' . $row, $item['icp_record']);
            $sheet->setCellValue('F' . $row, $item['version']);
            $sheet->setCellValue('G' . $row, $item['updated_at']);
        }
        $fileName = date('Ymd') . '_导出的信息管理列表.' . $format;
        if ($format == 'csv') {
            $writer = new Csv($spreadsheet);
            header('Content-Type: application/csv');
        } else {
            $writer = new Xlsx($spreadsheet);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        }
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }

   // 导入信息
   public function import()
   {
       // 获取上传文件
       $file = $this->request->file('file');
       if (!$file) {
           return json(['code' => 1, 'msg' => '请选择要上传的文件', 'data' => []]);
       }

       // 验证文件格式
       $allowExt = ['csv', 'xlsx', 'xls'];
       $ext = $file->getOriginalExtension();
       if (!in_array($ext, $allowExt)) {
           return json(['code' => 1, 'msg' => '仅支持CSV/Excel文件', 'data' => []]);
       }

       // 移动文件到临时目录
       $savePath = runtime_path() . 'import/';
       if (!is_dir($savePath)) {
           mkdir($savePath, 0755, true);
       }
       $filename = uniqid() . '.' . $ext; // 避免文件名冲突
       $file->move($savePath, $filename);
       $filePath = $savePath . $filename;

       try {
           // 读取文件内容
           $spreadsheet = IOFactory::load($filePath);
           $sheet = $spreadsheet->getActiveSheet();
           $rows = $sheet->toArray(); // 原始数据（可能包含null）

           // === 修复：全局替换null为空字符串 ===
           $rows = array_map(function ($row) {
               return array_map(fn ($v) => $v === null ? '' : $v, $row); // 核心修复
           }, $rows);

           $success = 0;
           $errors = [];
           $snowflake = new Snowflake(1, 1);

           // 校验表头
           $header = array_map('trim', $rows[0]);
           $requiredHeaders = ['ID', '雪花ID', '域名', '开发者', 'ICP备案', '版本号', '修改时间'];
           foreach ($requiredHeaders as $h) {
               if (!in_array($h, $header)) {
                   throw new \Exception("缺少必要表头：{$h}");
               }
           }

           // 从第二行开始处理
           for ($rowNum = 1; $rowNum < count($rows); $rowNum++) {
               $row = $rows[$rowNum]; // 已处理null为''
               if (empty(array_filter($row))) {
                   $errors[] = ['row' => $rowNum + 1, 'msg' => '数据为空行'];
                   continue;
               }

               // 按正确列顺序解析数据（使用?? ''确保非null）
               $data = [
                   'id' => $row[0] ?? '',
                   'snowflake_id' => $row[1] ?? '',
                   'domain' => $row[2] ?? '',
                   'developer' => $row[3] ?? '',
                   'icp_record' => $row[4] ?? '',
                   'version' => $row[5] ?? '',
                   'updated_at' => $row[6] ?? '',
               ];

               // === 数据转换 ===
               // 1. 生成snowflake_id
               if (empty($data['snowflake_id'])) {
                   $data['snowflake_id'] = $snowflake->nextId();
               }

               // === 数据验证 ===
               $validate = new \think\Validate([
                   'domain' => 'require',
                   'version' => 'require',
                   'developer' => 'require',
               ]);

               if (!$validate->check($data)) {
                   $errors[] = [
                       'row' => $rowNum + 1,
                       'msg' => $validate->getError()
                   ];
                   continue;
               }

               // === 唯一性校验 ===
               if (Db::name('website_info')->where('snowflake_id', $data['snowflake_id'])->find()) {
                   $errors[] = [
                       'row' => $rowNum + 1,
                       'msg' => "雪花ID已存在：{$data['snowflake_id']}"
                   ];
                   continue;
               }

               // 补充创建时间和更新时间
               $data['created_at'] = date('Y-m-d H:i:s');
               $data['updated_at'] = date('Y-m-d H:i:s');

               // === 写入数据库 ===
               try {
                   Db::name('website_info')->insert($data);
                   $success++;
               } catch (\Exception $e) {
                   $errors[] = [
                       'row' => $rowNum + 1,
                       'msg' => "数据库错误：{$e->getMessage()}"
                   ];
               }
           }

           // 删除临时文件
           @unlink($filePath);

           return json([
               'code' => 0,
               'msg' => "导入完成，成功{$success}条，失败" . count($errors) . "条",
               'data' => [
                   'success' => $success,
                   'errors' => $errors
               ]
           ]);

       } catch (\Exception $e) {
           @unlink($filePath);
           return json([
               'code' => 1,
               'msg' => "导入失败：{$e->getMessage()}",
               'data' => []
           ]);
       }
   }
}